package org.example.new_hbps_backend_reconstruction.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.new_hbps_backend_reconstruction.entity.AiPreDiagnosisEntity;
import org.example.new_hbps_backend_reconstruction.entity.PatientBaseEntity;
import org.example.new_hbps_backend_reconstruction.entity.PatientDoctorEntity;
import org.example.new_hbps_backend_reconstruction.entity.PersureHeartRateEntity;
import org.example.new_hbps_backend_reconstruction.mapper.*;
import org.example.new_hbps_backend_reconstruction.service.HeartRateLogsService;
import org.example.new_hbps_backend_reconstruction.service.PersureHeartRateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 丁利军
 * @date 2025年10月11日 16:11
 * @description 血压心率展示
 */

@Service
public class PersureHeartRateServiceImpl extends ServiceImpl<PersureHeartRateMapper, PersureHeartRateEntity> implements PersureHeartRateService {
    @Autowired
    private PersureHeartRateMapper persureHeartRateMapper;
    @Autowired
    private PatientBaseMapper patientBaseMapper;
    @Autowired
    private PatientDoctorMapper patientDoctorMapper;
    @Autowired
    private HeartRateLogsMapper heartRateLogsMapper;
    @Autowired
    private HeartRateLogsService heartRateLogsService;
    @Autowired
    private AiPreDiagnosisMapper aiPreDiagnosisMapper;
    private static final Logger logger = LoggerFactory.getLogger(PersureHeartRateService.class);

    @Override
    public void addBloodPressure(PersureHeartRateEntity persureHeartRate) {
        persureHeartRate = this.setSdhAndRiskClass(persureHeartRate);
        //   如果没有上传时间，再填充
        if(persureHeartRate.getUploadTime() == null) {
            persureHeartRate.setUploadTime(LocalDateTime.now());
        }
        persureHeartRateMapper.insert(persureHeartRate); // 使用 MyBatis-Plus 的 insert 方法
    }

    @Transactional
    @Override
    public void AddPressureInBatches(List<PersureHeartRateEntity> result) {
        for(PersureHeartRateEntity data : result) {
            //  设置sdh分类和risk分类
            this.setSdhAndRiskClass(data);
        }
        //  批量增加
        this.saveBatch(result);
    }

    @Override
    public PersureHeartRateEntity setSdhAndRiskClass(PersureHeartRateEntity persureHeartRate) {

        // 查询与患者相关的 AI 预问诊记录
        LambdaQueryWrapper<AiPreDiagnosisEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AiPreDiagnosisEntity::getPatientUid, persureHeartRate.getPatientUid());
        List<AiPreDiagnosisEntity> aiPreDiagnosisList = aiPreDiagnosisMapper.selectList(queryWrapper);

        // 使用 Map 存储每个患者的最新记录
        Map<Long, AiPreDiagnosisEntity> latestDiagnosisMap = new HashMap<>();
        for (AiPreDiagnosisEntity diagnosis : aiPreDiagnosisList) {
            Long patientUid = diagnosis.getPatientUid();
            if (!latestDiagnosisMap.containsKey(patientUid) || diagnosis.getAiId() > latestDiagnosisMap.get(patientUid).getAiId()) {
                latestDiagnosisMap.put(patientUid, diagnosis);
            }
        }

        // 获取当前患者的最新记录
        AiPreDiagnosisEntity latestDiagnosis = latestDiagnosisMap.get(persureHeartRate.getPatientUid());

        // 根据血压值和最新的 AI 预问诊记录判断分类
        String classification = determineClassification(persureHeartRate, latestDiagnosis);
        String riskAssessment = judgeRiskByBloodPressure(persureHeartRate.getSystolic(), persureHeartRate.getDiastolic());

        // 设置上传时间并插入血压记录
        persureHeartRate.setSdhClassification(classification);
        persureHeartRate.setRiskAssessment(riskAssessment);
        return persureHeartRate;
    }

    private String determineClassification(PersureHeartRateEntity heartRate, AiPreDiagnosisEntity diagnosis) {
        if (heartRate.getSystolic() >= 180 || heartRate.getDiastolic() >= 110) {
            return "三级高血压高危";
        } else if (heartRate.getSystolic() >= 160 && heartRate.getSystolic() <= 179 ||
                heartRate.getDiastolic() >= 100 && heartRate.getDiastolic() <= 109) {
            // 二级高血压逻辑
            if (diagnosis != null) {
                if (diagnosis.getIsClinical() != null && diagnosis.getIsClinical()) {
                    return "二级高血压高危";
                } else if (diagnosis.getDangerReason() != null && diagnosis.getDangerReason() <= 2) {
                    return "二级高血压中危";
                }
            }
            return "二级高血压高危";
        } else if (heartRate.getSystolic() >= 140 && heartRate.getSystolic() <= 159 ||
                heartRate.getDiastolic() >= 90 && heartRate.getDiastolic() <= 99) {
            // 一级高血压逻辑
            if (diagnosis != null) {
                if (diagnosis.getIsClinical() != null && diagnosis.getIsClinical()) {
                    return "一级高血压高危";
                } else if (diagnosis.getDangerReason() != null && diagnosis.getDangerReason() == 0) {
                    return "一级高血压低危";
                } else if (diagnosis.getDangerReason() != null && diagnosis.getDangerReason() <= 2) {
                    return "一级高血压中危";
                }
            }
            return "一级高血压高危";
        }
        return "未分类";
    }

    @Override
    public boolean savePersureHeartRate(PersureHeartRateEntity persureHeartRate) {
        String riskAssessment = judgeRiskByBloodPressure(persureHeartRate.getSystolic(), persureHeartRate.getDiastolic());
        persureHeartRate.setRiskAssessment(riskAssessment);
        return save(persureHeartRate);
    }

    @Override
    public JSONArray getDailyPressureDate(Long patientUid, LocalDate date) {
        QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("upload_time", date.atStartOfDay(), date.atTime(23, 59, 59))
                .eq("patient_uid", patientUid)
                .orderByAsc("upload_time");
        List<PersureHeartRateEntity> persureHeartRateEntities = persureHeartRateMapper.selectList(queryWrapper);

        JSONArray results = new JSONArray();
        for(PersureHeartRateEntity entity : persureHeartRateEntities) {
            JSONObject result = new JSONObject();

            result.put("time", entity.getUploadTime());
            result.put("systolic", entity.getSystolic());
            result.put("diastolic", entity.getDiastolic());
            result.put("pulsePressure", entity.getSystolic() - entity.getDiastolic());
            result.put("RiskAssessment", entity.getRiskAssessment());
            if(entity.getSystolic() - entity.getDiastolic()>60){
                result.put("pulsePressureRiskAssessment", "偏高");
            }else if(entity.getSystolic() - entity.getDiastolic()<30){
                result.put("pulsePressureRiskAssessment", "偏低");
            }else{
                result.put("pulsePressureRiskAssessment", "正常");
            }
            results.add(result);
        }
        return results;
    }

    @Override
    public String judgeRiskByBloodPressure(float systolic, float diastolic){
        if(systolic >= 180 || diastolic >= 110){
            return "重度";
        } else if(systolic >= 160 || diastolic >= 100){
            return "中度";
        } else if(systolic >= 140 || diastolic >= 90){
            return "轻度";
        } else if(systolic >= 120 || diastolic >= 80){
            return "正常高值";
        } else if(systolic >= 90 && diastolic >= 60){
            return "正常";
        } else {
            return "偏低";
        }
    }
    public String judgeRiskByBloodPressureSystolic(float systolic){
        if(systolic >= 180){
            return "重度";
        } else if(systolic >= 160){
            return "中度";
        } else if(systolic >= 140){
            return "轻度";
        } else if(systolic >= 120 ){
            return "正常高值";
        } else if(systolic >= 90){
            return "正常";
        } else if(systolic >= 0){
            return "偏低";
        }else{
            return null;
        }
    }
    public String judgeRiskByBloodPressureDiastolic( float diastolic){

        if( diastolic >= 110){
            return "重度";
        } else if( diastolic >= 100){
            return "中度";
        } else if( diastolic >= 90){
            return "轻度";
        } else if( diastolic >= 80){
            return "正常高值";
        } else if( diastolic >= 60){
            return "正常";
        } else if( diastolic >= 0){
            return "偏低";
        }else{
            return null;
        }
    }


    @Override
    public JSONObject classifyAllBloodPressure(Long patientUid){
        LambdaQueryWrapper<PersureHeartRateEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PersureHeartRateEntity::getPatientUid, patientUid);

        List<PersureHeartRateEntity> records = persureHeartRateMapper.selectList(queryWrapper);

        int severe = 0, moderate = 0, mild = 0, elevated = 0, low = 0, all = 0;

        for(PersureHeartRateEntity record : records){
            float systolic = record.getSystolic(); // 收缩压 高压
            float diastolic = record.getDiastolic(); // 舒张压 低压

            String risk = judgeRiskByBloodPressure(systolic, diastolic);
            switch(risk){
                case "重度": severe++;
                case "中度": moderate++;
                case "轻度": mild++;
                case "正常高值": elevated++;
                case "偏低": low++;
            }
            all++;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("severe", severe);
        jsonObject.put("moderate", moderate);
        jsonObject.put("mild", mild);
        jsonObject.put("elevated", elevated);
        jsonObject.put("low", low);
        jsonObject.put("all", all);

        return jsonObject;
    }

    @Override
    public String getCurrentRiskAssessment(Long patientUid){
        LambdaQueryWrapper<PersureHeartRateEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PersureHeartRateEntity::getPatientUid, patientUid)
                .orderByDesc(PersureHeartRateEntity::getUploadTime)
                .last("limit 1");
        float systolic = (persureHeartRateMapper.selectOne(queryWrapper)).getSystolic(); // 高压
        float diastolic = (persureHeartRateMapper.selectOne(queryWrapper)).getDiastolic(); // 低压
        return judgeRiskByBloodPressure(systolic, diastolic);
    }

    @Override
    public JSONArray getWeeklyPressureData(int weeksAgo, Long patientUid) {
        LocalDate date = LocalDate.now();
        LocalDate startOfWeek = date.minusWeeks(weeksAgo + 1).with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = startOfWeek.plusDays(6);

        QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("upload_time", startOfWeek.atStartOfDay(), endOfWeek.atTime(23, 59, 59))
                .eq("patient_uid", patientUid);

        List<PersureHeartRateEntity> weeklyRecords = persureHeartRateMapper.selectList(queryWrapper);

        Map<LocalDate, List<PersureHeartRateEntity>> recordsByDate = weeklyRecords.stream()
                .collect(Collectors.groupingBy(record -> record.getUploadTime().toLocalDate()));

        Map<LocalDate, JSONObject> sortedDailyData = new TreeMap<>();

        for (Map.Entry<LocalDate, List<PersureHeartRateEntity>> entry : recordsByDate.entrySet()) {
            LocalDate recordDate = entry.getKey();
            JSONArray systolicArray = new JSONArray();
            JSONArray diastolicArray = new JSONArray();
            JSONArray riskAssessmentArray = new JSONArray();
            JSONArray plusePressureArray = new JSONArray();

            for (PersureHeartRateEntity record : entry.getValue()) {
                systolicArray.add(record.getSystolic() != null ? record.getSystolic() : null);
                diastolicArray.add(record.getDiastolic() != null ? record.getDiastolic() : null);
                riskAssessmentArray.add(record.getRiskAssessment() != null ? record.getRiskAssessment() : null);
                if(record.getSystolic() != null && record.getDiastolic() != null){
                    plusePressureArray.add(record.getSystolic()-record.getDiastolic());
                }else{
                    plusePressureArray.add(null);
                }
            }

            JSONObject dailyData = new JSONObject();
            dailyData.put("systolic", systolicArray);
            dailyData.put("diastolic", diastolicArray);
            dailyData.put("riskAssessment", riskAssessmentArray);
            dailyData.put("plusePressure", plusePressureArray);
            dailyData.put("date", recordDate);

            sortedDailyData.put(recordDate, dailyData);
        }

        // 确保一周的每天都有数据，即使其中某天没有血压和心率数据
        for (LocalDate day = startOfWeek; !day.isAfter(endOfWeek); day = day.plusDays(1)) {
            if (!sortedDailyData.containsKey(day)) {
                JSONObject emptyData = new JSONObject();
                emptyData.put("systolic", new JSONArray());
                emptyData.put("diastolic", new JSONArray());
                emptyData.put("riskAssessment", new JSONArray());
                emptyData.put("plusePressure", new JSONArray());
                emptyData.put("date", day);
                sortedDailyData.put(day, emptyData);
            }
        }
        JSONArray pressureData = new JSONArray();
        pressureData.addAll(sortedDailyData.values());

        return pressureData;
    }

    @Override
    public JSONArray getMonthlyPressureData(int monthsAgo, Long patientUid) {
        LocalDate date = LocalDate.now();
        LocalDate startOfMonth = date.minusMonths(monthsAgo).withDayOfMonth(1);
        LocalDate endOfMonth = startOfMonth.with(TemporalAdjusters.lastDayOfMonth());

        QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("upload_time", startOfMonth.atStartOfDay(), endOfMonth.atTime(23, 59, 59))
                .eq("patient_uid", patientUid);

        List<PersureHeartRateEntity> monthlyRecords = persureHeartRateMapper.selectList(queryWrapper);

        Map<LocalDate, List<PersureHeartRateEntity>> recordsByDate = monthlyRecords.stream()
                .collect(Collectors.groupingBy(record -> record.getUploadTime().toLocalDate()));

        Map<LocalDate, JSONObject> sortedDailyData = new TreeMap<>();

        for (Map.Entry<LocalDate, List<PersureHeartRateEntity>> entry : recordsByDate.entrySet()) {
            LocalDate recordDate = entry.getKey();
            JSONArray systolicArray = new JSONArray();
            JSONArray diastolicArray = new JSONArray();
            JSONArray riskAssessmentArray = new JSONArray();
            JSONArray plusePressureArray = new JSONArray();


            for (PersureHeartRateEntity record : entry.getValue()) {
                systolicArray.add(record.getSystolic() != null ? record.getSystolic() : null);
                diastolicArray.add(record.getDiastolic() != null ? record.getDiastolic() : null);
                riskAssessmentArray.add(record.getRiskAssessment() != null ? record.getRiskAssessment() : null);
                if(record.getSystolic() != null && record.getDiastolic() != null){
                    plusePressureArray.add(record.getSystolic()-record.getDiastolic());
                }else{
                    plusePressureArray.add(null);
                }

            }

            JSONObject dailyData = new JSONObject();
            dailyData.put("systolic", systolicArray);
            dailyData.put("diastolic", diastolicArray);
            dailyData.put("riskAssessment", riskAssessmentArray);
            dailyData.put("plusePressure", plusePressureArray);
            dailyData.put("date", recordDate);

            sortedDailyData.put(recordDate, dailyData);
        }

        for (LocalDate day = startOfMonth; !day.isAfter(endOfMonth); day = day.plusDays(1)) {
            if (!sortedDailyData.containsKey(day)) {
                JSONObject emptyData = new JSONObject();
                emptyData.put("systolic", new JSONArray());
                emptyData.put("diastolic", new JSONArray());
                emptyData.put("riskAssessment", new JSONArray());
                emptyData.put("plusePressure", new JSONArray());
                emptyData.put("date", day);
                sortedDailyData.put(day, emptyData);
            }
        }
        JSONArray pressureData = new JSONArray();
        pressureData.addAll(sortedDailyData.values());

        return pressureData;
    }


    @Override
    public JSONArray getYearlyPressureData(int yearsAgo, Long patientUid) {
        LocalDate date = LocalDate.now();
        LocalDate startOfYear = date.minusYears(yearsAgo).withDayOfYear(1);
        LocalDate endOfYear = startOfYear.with(TemporalAdjusters.lastDayOfYear());

        QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("upload_time", startOfYear.atStartOfDay(), endOfYear.atTime(23, 59, 59))
                .eq("patient_uid", patientUid);

        List<PersureHeartRateEntity> yearlyRecords = persureHeartRateMapper.selectList(queryWrapper);

        Map<LocalDate, List<PersureHeartRateEntity>> recordsByDate = yearlyRecords.stream()
                .collect(Collectors.groupingBy(record -> record.getUploadTime().toLocalDate()));

        Map<LocalDate, JSONObject> sortedDailyData = new TreeMap<>();

        for (Map.Entry<LocalDate, List<PersureHeartRateEntity>> entry : recordsByDate.entrySet()) {
            LocalDate recordDate = entry.getKey();
            JSONArray systolicArray = new JSONArray();
            JSONArray diastolicArray = new JSONArray();
            JSONArray riskAssessmentArray = new JSONArray();
            JSONArray plusePressureArray = new JSONArray();

            for (PersureHeartRateEntity record : entry.getValue()) {
                systolicArray.add(record.getSystolic() != null ? record.getSystolic() : null);
                diastolicArray.add(record.getDiastolic() != null ? record.getDiastolic() : null);
            }

            JSONObject dailyData = new JSONObject();
            dailyData.put("systolic", systolicArray);
            dailyData.put("diastolic", diastolicArray);
            dailyData.put("riskAssessment", riskAssessmentArray);
            dailyData.put("plusePressure", plusePressureArray);
            dailyData.put("date", recordDate);

            sortedDailyData.put(recordDate, dailyData);
        }

        for (LocalDate day = startOfYear; !day.isAfter(endOfYear); day = day.plusDays(1)) {
            if (!sortedDailyData.containsKey(day)) {
                JSONObject emptyData = new JSONObject();
                emptyData.put("systolic", new JSONArray());
                emptyData.put("diastolic", new JSONArray());
                emptyData.put("riskAssessment", new JSONArray());
                emptyData.put("plusePressure", new JSONArray());
                emptyData.put("date", day);
                sortedDailyData.put(day, emptyData);
            }
        }
        JSONArray pressureData = new JSONArray();
        pressureData.addAll(sortedDailyData.values());

        return pressureData;
    }



    @Override
    public PersureHeartRateEntity getTodayMaxBloodPressure(Long patientUid) {
        return persureHeartRateMapper.selectTodayMaxBloodPressure(patientUid);
    }

    @Override
    public PersureHeartRateEntity getTodayMinHeartRate(Long patientUid) {
        return persureHeartRateMapper.selectTodayMinHeartRate(patientUid);
    }

    @Override
    public JSONArray getDailyConsecutiveAbnormalities(Long doctorUid) {
        LocalDate date = LocalDate.now();
        LocalDateTime startOfDay = date.atStartOfDay();
        LocalDateTime endOfDay = date.atTime(23, 59, 59);

        QueryWrapper<PatientDoctorEntity> doctorQueryWrapper = new QueryWrapper<>();
        doctorQueryWrapper.eq("doctor_uid", doctorUid);

        List<Long> patientUids = patientDoctorMapper.selectList(doctorQueryWrapper)
                .stream()
                .map(PatientDoctorEntity::getPatientUid)
                .toList();

        if (patientUids.isEmpty()) {
            return new JSONArray();
        }

        // 根据患者UID列表查询心率记录
        QueryWrapper<PersureHeartRateEntity> heartRateQueryWrapper = new QueryWrapper<>();
        heartRateQueryWrapper.between("upload_time", startOfDay, endOfDay)
                .in("patient_uid", patientUids);



        List<PersureHeartRateEntity> todayRecords = persureHeartRateMapper.selectList(heartRateQueryWrapper);

        // 建立patient_uid和PatientBaseEntity之间的映射，便于后续查询患者基本信息
        Map<Long, PatientBaseEntity> patientBaseMap = patientBaseMapper.selectList(new QueryWrapper<>())
                .stream()
                .collect(Collectors.toMap(PatientBaseEntity::getPatientUid, Function.identity()));

        // 建立patient_uid和PersureHeartRateEntity之间的映射，便于后续按患者统计心率血压异常次数
        Map<Long, List<PersureHeartRateEntity>> recordsByPatient = todayRecords.stream()
                .collect(Collectors.groupingBy(PersureHeartRateEntity::getPatientUid));

        JSONArray result = new JSONArray();

        for (Map.Entry<Long, List<PersureHeartRateEntity>> entry : recordsByPatient.entrySet()) {
            Long patientUid = entry.getKey();
            List<PersureHeartRateEntity> records = entry.getValue();
            records.sort(Comparator.comparing(PersureHeartRateEntity::getUploadTime));

            List<JSONObject> patientDataList = new ArrayList<>();

            int consecutiveHighBp = 0; // 连续高压超过180的次数
            LocalDateTime highBpStart = null;
            LocalDateTime highBpEnd = null;


            for (PersureHeartRateEntity record : records) {
                if (record.getSystolic() >= 180 || record.getDiastolic() >= 110) {
                    if (consecutiveHighBp == 0) {
                        highBpStart = record.getUploadTime();
                    }
                    consecutiveHighBp++;
                    highBpEnd = record.getUploadTime();
                } else {
                    if (consecutiveHighBp > 1) {
                        JSONObject patientData = new JSONObject();
                        PatientBaseEntity patientBase = patientBaseMap.get(patientUid);
                        LocalDate birthday = patientBase.getBirthday();
                        LocalDate current = LocalDate.now();
                        int age = 0;
                        if (birthday != null) {
                            age = Period.between(birthday, current).getYears();
                        }

                        patientData.put("name", patientBase.getPatientName());
                        patientData.put("sex", patientBase.getSex());
                        patientData.put("age", age);
                        patientData.put("abnormality", "血压高于180/110mmHg");
                        patientData.put("ill", "高压过高");
                        patientData.put("count", consecutiveHighBp);
                        patientData.put("duration", String.format("%d小时%d分钟",
                                Duration.between(highBpStart, highBpEnd).toHours(),
                                Duration.between(highBpStart, highBpEnd).toMinutes() % 60));

                        patientDataList.add(patientData);
                    }
                    consecutiveHighBp = 0;
                }
            }

            // 处理最后一条记录后的未记录异常情况
            if (consecutiveHighBp > 1) {
                JSONObject patientData = new JSONObject();
                PatientBaseEntity patientBase = patientBaseMap.get(patientUid);
                LocalDate birthday = patientBase.getBirthday();
                LocalDate current = LocalDate.now();
                int age = 0;
                if (birthday != null) {
                    age = Period.between(birthday, current).getYears();
                }

                patientData.put("name", patientBase.getPatientName());
                patientData.put("sex", patientBase.getSex());
                patientData.put("age", age);
                patientData.put("abnormality", "血压高于180/110mmHg");
                patientData.put("ill", "高压过高");
                patientData.put("count", consecutiveHighBp);
                patientData.put("duration", String.format("%d小时%d分钟",
                        Duration.between(highBpStart, highBpEnd).toHours(),
                        Duration.between(highBpStart, highBpEnd).toMinutes() % 60));

                patientDataList.add(patientData);
            }

            result.addAll(patientDataList);
        }

        result.sort((a, b) -> ((Integer) ((JSONObject) b).get("count")).compareTo((Integer) ((JSONObject) a).get("count")));
        return result;
    }


    public JSONObject getMaxMinAvgSystolic(LocalDateTime start, LocalDateTime end, Long patientUid) {
        QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_uid", patientUid)
                .between("upload_time", start, end);

        List<PersureHeartRateEntity> records = persureHeartRateMapper.selectList(queryWrapper);

        DoubleSummaryStatistics systolicStats = records.stream()
                .mapToDouble(PersureHeartRateEntity::getSystolic)
                .summaryStatistics();

        Optional<PersureHeartRateEntity> maxSystolicRecord = records.stream()
                .max((record1, record2) -> Float.compare(record1.getSystolic(), record2.getSystolic()));
        Optional<PersureHeartRateEntity> minSystolicRecord = records.stream()
                .min((record1, record2) -> Float.compare(record1.getSystolic(), record2.getSystolic()));

        JSONObject result = new JSONObject();
        result.put("max_systolic", maxSystolicRecord.map(PersureHeartRateEntity::getSystolic).orElse(null));
        result.put("max_systolic_risk_assessment",judgeRiskByBloodPressureSystolic(maxSystolicRecord.get().getSystolic()));
        result.put("max_diastolic", maxSystolicRecord.map(PersureHeartRateEntity::getDiastolic).orElse(null));
        result.put("min_systolic", minSystolicRecord.map(PersureHeartRateEntity::getSystolic).orElse(null));
        result.put("min_systolic_risk_assessment",judgeRiskByBloodPressureSystolic(minSystolicRecord.get().getSystolic()));
        result.put("min_diastolic", minSystolicRecord.map(PersureHeartRateEntity::getDiastolic).orElse(null));
        result.put("avg_systolic", systolicStats.getAverage());
        result.put("avg_systolic_risk_assessment", judgeRiskByBloodPressureSystolic((float) systolicStats.getAverage()));
//        result.put("avg_diastolic", systolicStats.getAverage());
//        result.put("avg_diastolic_risk_assessment", judgeRiskByBloodPressureDiastolic((float) systolicStats.getAverage()));
        return result;
    }

    public JSONObject getMaxMinAvgDiastolic(LocalDateTime start, LocalDateTime end, Long patientUid) {
        QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_uid", patientUid)
                .between("upload_time", start, end);

        List<PersureHeartRateEntity> records = persureHeartRateMapper.selectList(queryWrapper);

        DoubleSummaryStatistics diastolicStats = records.stream()
                .mapToDouble(PersureHeartRateEntity::getDiastolic)
                .summaryStatistics();

        Optional<PersureHeartRateEntity> maxDiastolicRecord = records.stream()
                .max((record1, record2) -> Float.compare(record1.getDiastolic(), record2.getDiastolic()));
        Optional<PersureHeartRateEntity> minDiastolicRecord = records.stream()
                .min((record1, record2) -> Float.compare(record1.getDiastolic(), record2.getDiastolic()));

        JSONObject result = new JSONObject();
        result.put("max_diastolic", maxDiastolicRecord.map(PersureHeartRateEntity::getDiastolic).orElse(null));
        result.put("max_diastolic_risk_assessment",judgeRiskByBloodPressureDiastolic(maxDiastolicRecord.get().getDiastolic()));
        result.put("max_systolic", maxDiastolicRecord.map(PersureHeartRateEntity::getSystolic).orElse(null));
        result.put("min_diastolic", minDiastolicRecord.map(PersureHeartRateEntity::getDiastolic).orElse(null));
        result.put("min_diastolic_risk_assessment",judgeRiskByBloodPressureDiastolic(maxDiastolicRecord.get().getDiastolic()));
        result.put("min_systolic", minDiastolicRecord.map(PersureHeartRateEntity::getSystolic).orElse(null));
        result.put("avg_diastolic", diastolicStats.getAverage());
        result.put("avg_diastolic_risk_assessment", judgeRiskByBloodPressureDiastolic((float) diastolicStats.getAverage()));
        return result;
    }

    @Override
    public JSONObject getDailyMaxMinAvgSystolic(LocalDate date, Long patientUid) {
        LocalDateTime startOfDay = date.atStartOfDay();
        LocalDateTime endOfDay = date.atTime(LocalTime.MAX);
        return getMaxMinAvgSystolic(startOfDay, endOfDay, patientUid);
    }

    @Override
    public JSONObject getDailyMaxMinAvgDiastolic(LocalDate date, Long patientUid) {
        LocalDateTime startOfDay = date.atStartOfDay();
        LocalDateTime endOfDay = date.atTime(LocalTime.MAX);
        return getMaxMinAvgDiastolic(startOfDay, endOfDay, patientUid);
    }

    @Override
    public JSONObject getWeeklyMaxMinAvgSystolic(LocalDate anyDateInWeek, Long patientUid) {
//        LocalDate startOfWeek = anyDateInWeek.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
//        LocalDate endOfWeek = anyDateInWeek.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        LocalDate startOfWeek = anyDateInWeek.minusDays(6);
        // 向前推6天
        LocalDate endOfWeek = anyDateInWeek;
        // 当天为结束日

        LocalDateTime startDateTime = startOfWeek.atStartOfDay();
        LocalDateTime endDateTime = endOfWeek.atTime(LocalTime.MAX);

        return getMaxMinAvgSystolic(startDateTime, endDateTime, patientUid);
    }

    @Override
    public JSONObject getWeeklyMaxMinAvgDiastolic(LocalDate anyDateInWeek, Long patientUid) {
//        LocalDate startOfWeek = anyDateInWeek.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
//        LocalDate endOfWeek = anyDateInWeek.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        LocalDate startOfWeek = anyDateInWeek.minusDays(6);
        // 向前推6天
        LocalDate endOfWeek = anyDateInWeek;
        // 当天为结束日
        LocalDateTime startDateTime = startOfWeek.atStartOfDay();
        LocalDateTime endDateTime = endOfWeek.atTime(LocalTime.MAX);

        return getMaxMinAvgDiastolic(startDateTime, endDateTime, patientUid);
    }

    @Override
    public JSONObject getMonthlyMaxMinAvgSystolic(YearMonth month, Long patientUid) {
        LocalDate startOfMonth = month.atDay(1);
        LocalDate endOfMonth = month.atEndOfMonth();

        LocalDateTime startDateTime = startOfMonth.atStartOfDay();
        LocalDateTime endDateTime = endOfMonth.atTime(LocalTime.MAX);

        return getMaxMinAvgSystolic(startDateTime, endDateTime, patientUid);
    }

    @Override
    public JSONObject getMonthlyMaxMinAvgDiastolic(YearMonth month, Long patientUid) {
        LocalDate startOfMonth = month.atDay(1);
        LocalDate endOfMonth = month.atEndOfMonth();

        LocalDateTime startDateTime = startOfMonth.atStartOfDay();
        LocalDateTime endDateTime = endOfMonth.atTime(LocalTime.MAX);

        return getMaxMinAvgDiastolic(startDateTime, endDateTime, patientUid);
    }


    @Override
    public JSONObject getYearlyMaxMinAvgSystolic(Long patientUid) {
        LocalDate date = LocalDate.now();
        LocalDateTime startOfYear = date.withDayOfYear(1).atStartOfDay();
        LocalDateTime endOfYear = date.with(TemporalAdjusters.lastDayOfYear()).atTime(23, 59, 59);
        return getMaxMinAvgSystolic(startOfYear, endOfYear, patientUid);
    }

    @Override
    public JSONObject getYearlyMaxMinAvgDiastolic(Long patientUid) {
        LocalDate date = LocalDate.now();
        LocalDateTime startOfYear = date.withDayOfYear(1).atStartOfDay();
        LocalDateTime endOfYear = date.with(TemporalAdjusters.lastDayOfYear()).atTime(23, 59, 59);
        return getMaxMinAvgDiastolic(startOfYear, endOfYear, patientUid);
    }

    public String judgePressureDiff(float pressureDiff) {
        String state;
        if(pressureDiff < 20) {
            state = "过小";
        } else if(pressureDiff < 60) {
            state = "正常";
        } else if(pressureDiff >= 60){
            state = "过大";
        }else{
            state = "未知";
        }
        return state;
    }

    public JSONObject getMaxMinAvgPressureDiff(LocalDateTime start, LocalDateTime end, Long patientUid) {
        QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_uid", patientUid)
                .between("upload_time", start, end);

        List<PersureHeartRateEntity> records = persureHeartRateMapper.selectList(queryWrapper);

        DoubleSummaryStatistics pulsePressureStats = records.stream()
                .mapToDouble(record -> record.getSystolic() - record.getDiastolic())
                .summaryStatistics();

        Optional<PersureHeartRateEntity> maxPulsePressureRecord = records.stream()
                .max((record1, record2) -> Float.compare(record1.getSystolic() - record1.getDiastolic(), record2.getSystolic() - record2.getDiastolic()));
        Optional<PersureHeartRateEntity> minPulsePressureRecord = records.stream()
                .min((record1, record2) -> Float.compare(record1.getSystolic() - record1.getDiastolic(), record2.getSystolic() - record2.getDiastolic()));


        JSONObject result = new JSONObject();
        result.put("max_pulse_pressure", maxPulsePressureRecord.map(record -> record.getSystolic() - record.getDiastolic()).orElse(null));
        result.put("max_pulse_pressure_systolic", maxPulsePressureRecord.map(PersureHeartRateEntity::getSystolic).orElse(null));
        result.put("max_pulse_pressure_diastolic", maxPulsePressureRecord.map(PersureHeartRateEntity::getDiastolic).orElse(null));
        maxPulsePressureRecord.ifPresent(record -> {
            float maxPulsePressure = record.getSystolic() - record.getDiastolic();
            result.put("max_pulse_pressure_state", judgePressureDiff(maxPulsePressure));
        });

        result.put("min_pulse_pressure", minPulsePressureRecord.map(record -> record.getSystolic() - record.getDiastolic()).orElse(null));
        result.put("min_pulse_pressure_systolic", minPulsePressureRecord.map(PersureHeartRateEntity::getSystolic).orElse(null));
        result.put("min_pulse_pressure_diastolic", minPulsePressureRecord.map(PersureHeartRateEntity::getDiastolic).orElse(null));
        minPulsePressureRecord.ifPresent(record -> {
            float minPulsePressure = record.getSystolic() - record.getDiastolic();
            result.put("min_pulse_pressure_state", judgePressureDiff(minPulsePressure));
        });

        result.put("avg_pulse_pressure", pulsePressureStats.getAverage());
        result.put("avg_pulse_pressure_state", judgePressureDiff((float) pulsePressureStats.getAverage()));

        return result;
    }

    @Override
    public JSONObject getDailyMaxMinAvgPressureDiff(LocalDate date, Long patientUid) {
        LocalDateTime startOfDay = date.atStartOfDay();
        LocalDateTime endOfDay = date.atTime(LocalTime.MAX);
        return getMaxMinAvgPressureDiff(startOfDay, endOfDay, patientUid);
    }

    @Override
    public JSONObject getWeeklyMaxMinAvgPressureDiff(LocalDate anyDateInWeek, Long patientUid) {
        // 计算给定日期所在的周的开始和结束日期
        /*LocalDate startOfWeek = anyDateInWeek.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = anyDateInWeek.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));*/
        LocalDate startOfWeek = anyDateInWeek.minusDays(6);
        // 向前推6天
        LocalDate endOfWeek = anyDateInWeek;
        // 当天为结束日


        LocalDateTime startDateTime = startOfWeek.atStartOfDay();
        LocalDateTime endDateTime = endOfWeek.atTime(LocalTime.MAX);

        return getMaxMinAvgPressureDiff(startDateTime, endDateTime, patientUid);
    }

    @Override
    public JSONObject getMonthlyMaxMinAvgPressureDiff(YearMonth month, Long patientUid) {
        // 计算给定月份的开始和结束日期
        LocalDate startOfMonth = month.atDay(1);
        LocalDate endOfMonth = month.atEndOfMonth();

        LocalDateTime startDateTime = startOfMonth.atStartOfDay();
        LocalDateTime endDateTime = endOfMonth.atTime(LocalTime.MAX);

        return getMaxMinAvgPressureDiff(startDateTime, endDateTime, patientUid);
    }


    @Override
    public JSONObject getYearlyMaxMinAvgPressureDiff(Long patientUid) {
        LocalDate date = LocalDate.now();
        LocalDateTime startOfYear = date.withDayOfYear(1).atStartOfDay();
        LocalDateTime endOfYear = date.with(TemporalAdjusters.lastDayOfYear()).atTime(23, 59, 59);
        return getMaxMinAvgPressureDiff(startOfYear, endOfYear, patientUid);
    }

    @Override
    public String getWeekRangeByDate(LocalDate date) {
        LocalDate startOfWeek = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = startOfWeek.plusDays(6);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M月d日");
        String formattedStart = startOfWeek.format(formatter);
        String formattedEnd = endOfWeek.format(formatter);
        String result = formattedStart + "~" + formattedEnd;
        return result;
    }


    @Override
    public JSONObject getLatestMeasurementTime(Long patientUid) {
        LocalDateTime latestPressureTime = LocalDateTime.parse(getNewlyPressureData(patientUid)
                .getString("时间"));
        LocalDateTime latestHeartRateTime = LocalDateTime.parse(heartRateLogsService.getNewlyHeartRateData(patientUid)
                .getString("时间"));
        LocalDateTime latestTime = null;
        String source = "";

        // 比较两个时间并选择最新的
        if (latestPressureTime != null && latestHeartRateTime != null) {
            if (latestPressureTime.isAfter(latestHeartRateTime)) {
                latestTime = latestPressureTime;
                source = "Blood Pressure";
            } else {
                latestTime = latestHeartRateTime;
                source = "Heart Rate";
            }
        } else if (latestPressureTime != null) {
            latestTime = latestPressureTime;
            source = "Blood Pressure";
        } else if (latestHeartRateTime != null) {
            latestTime = latestHeartRateTime;
            source = "Heart Rate";
        }

        // 如果两个数据都没有测量时间
        if (latestTime == null) {
            throw new RuntimeException("No measurement data available for the patient.");
        }

        // 构建返回结果
        JSONObject result = new JSONObject();
        result.put("latestTime", latestTime.toString());
        result.put("source", source);

        return result;
    }

    @Override
    public JSONObject getDailyAveragePressureHeartRate(LocalDate date, Long patientUid) {
        LocalDateTime startOfDay = date.atStartOfDay();
        LocalDateTime endOfDay = date.atTime(23, 59, 59);

        QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_uid", patientUid)
                .between("upload_time", startOfDay, endOfDay);

        List<PersureHeartRateEntity> records = persureHeartRateMapper.selectList(queryWrapper);
        JSONObject result = new JSONObject();

        if (records.isEmpty()) {
            result.put("avg_systolic", 0);
            result.put("avg_diastolic", 0);
            result.put("avg_systolic_risk_assessment","偏低");
            result.put("avg_diastolic_risk_assessment","偏低");
        } else {
            DoubleSummaryStatistics systolicStats = records.stream()
                    .mapToDouble(PersureHeartRateEntity::getSystolic)
                    .summaryStatistics();

            DoubleSummaryStatistics diastolicStats = records.stream()
                    .mapToDouble(PersureHeartRateEntity::getDiastolic)
                    .summaryStatistics();

            double avgSystolic = systolicStats.getCount() > 0 ? systolicStats.getAverage() : 0;
            double avgDiastolic = diastolicStats.getCount() > 0 ? diastolicStats.getAverage() : 0;
            result.put("avg_systolic", avgSystolic);
            result.put("avg_diastolic", avgDiastolic);
            result.put("avg_systolic_risk_assessment", judgeRiskByBloodPressureSystolic((float) avgSystolic));
            result.put("avg_diastolic_risk_assessment", judgeRiskByBloodPressureSystolic((float) avgDiastolic));
        }

        return result;
    }

    @Override
    public JSONArray getWeeklyAveragePressureHeartRateByDay(LocalDate anyDateInWeek, Long patientUid) {
        // 计算给定日期所在的星期的开始和结束日期
        LocalDate startOfWeek = anyDateInWeek.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = startOfWeek.plusDays(6);

        JSONArray result = new JSONArray();

        // 循环计算这一周的每天的血压平均值
        for (LocalDate currentDate = startOfWeek; !currentDate.isAfter(endOfWeek); currentDate = currentDate.plusDays(1)) {
            JSONObject dailyAverage = getDailyAveragePressureHeartRate(currentDate, patientUid);
            dailyAverage.put("date", currentDate);

            result.add(dailyAverage);
        }

        return result;
    }

    @Override
    public JSONArray getMonthlyAveragePressureHeartRateByWeek(YearMonth month, Long patientUid) {
        // 获取这个月份的开始和结束日期
        LocalDate startOfMonth = month.atDay(1);
        LocalDate endOfMonth = month.atEndOfMonth();

        JSONArray monthlyPressureData = new JSONArray();

        LocalDate startOfWeek = startOfMonth;
        while (!startOfWeek.isAfter(endOfMonth)) {
            // 获取当前周的结束日期
            LocalDate endOfWeek = startOfWeek.with(DayOfWeek.SUNDAY);
            if (endOfWeek.isAfter(endOfMonth)) {
                endOfWeek = endOfMonth;
            }

            LocalDateTime startDateTime = startOfWeek.atStartOfDay();
            LocalDateTime endDateTime = endOfWeek.atTime(23, 59, 59);

            QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("patient_uid", patientUid)
                    .between("upload_time", startDateTime, endDateTime);

            List<PersureHeartRateEntity> weeklyRecords = persureHeartRateMapper.selectList(queryWrapper);

            DoubleSummaryStatistics systolicStats = weeklyRecords.stream()
                    .mapToDouble(PersureHeartRateEntity::getSystolic)
                    .summaryStatistics();

            DoubleSummaryStatistics diastolicStats = weeklyRecords.stream()
                    .mapToDouble(PersureHeartRateEntity::getDiastolic)
                    .summaryStatistics();

            JSONObject weeklyAverage = new JSONObject();
            weeklyAverage.put("start_date", startOfWeek.toString());
            weeklyAverage.put("end_date", endOfWeek.toString());
            weeklyAverage.put("avg_systolic", systolicStats.getCount() > 0 ? systolicStats.getAverage() : 0);
            weeklyAverage.put("avg_diastolic", diastolicStats.getCount() > 0 ? diastolicStats.getAverage() : 0);
            monthlyPressureData.add(weeklyAverage);

            // 进入下一周
            startOfWeek = endOfWeek.plusDays(1);
        }

        return monthlyPressureData;
    }


    @Override
    public JSONArray getYearlyAveragePressureHeartRateByMonth(int yearsAgo, Long patientUid) {
        LocalDate date = LocalDate.now();
        LocalDate startOfYear = date.minusYears(yearsAgo).withDayOfYear(1);
        int year = startOfYear.getYear();

        JSONArray yearlyPressureData = new JSONArray();
        for (int month = 1; month <= 12; month++) {
            LocalDate startOfMonth = LocalDate.of(year, month, 1);
            LocalDate endOfMonth = startOfMonth.with(TemporalAdjusters.lastDayOfMonth());

            LocalDateTime startDateTime = startOfMonth.atStartOfDay();
            LocalDateTime endDateTime = endOfMonth.atTime(23, 59, 59);

            QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("patient_uid", patientUid)
                    .between("upload_time", startDateTime, endDateTime);

            List<PersureHeartRateEntity> monthlyRecords = persureHeartRateMapper.selectList(queryWrapper);

            DoubleSummaryStatistics systolicStats = monthlyRecords.stream()
                    .mapToDouble(PersureHeartRateEntity::getSystolic)
                    .summaryStatistics();

            DoubleSummaryStatistics diastolicStats = monthlyRecords.stream()
                    .mapToDouble(PersureHeartRateEntity::getDiastolic)
                    .summaryStatistics();

            JSONObject monthlyAverage = new JSONObject();
            monthlyAverage.put("month", startOfMonth.getMonth().toString());
            monthlyAverage.put("avg_systolic", systolicStats.getCount() > 0 ? systolicStats.getAverage() : null);
            monthlyAverage.put("avg_diastolic", diastolicStats.getCount() > 0 ? diastolicStats.getAverage() : null);

            yearlyPressureData.add(monthlyAverage);
        }
        return yearlyPressureData;
    }

    @Override
    public JSONObject getNewlyPressureData(Long patientUid) {
        PersureHeartRateEntity measure =  persureHeartRateMapper.getLatestMeasurement(patientUid);
        if(measure==null){
            measure = new PersureHeartRateEntity();
            measure.setPatientUid(patientUid);
            measure.setUploadTime(LocalDateTime.now());
            measure.setSystolic(0.0f);
            measure.setDiastolic(0.0f);
            measure.setRiskAssessment("没有数据");
        }
        JSONObject data = new JSONObject();
        data.put("收缩压", measure.getSystolic());
        data.put("舒张压", measure.getDiastolic());
        data.put("风险评估", measure.getRiskAssessment());
        data.put("脉压差", measure.getSystolic() - measure.getDiastolic());
        if(measure.getSystolic() - measure.getDiastolic()>60){
            data.put("脉压差风险评估", "偏高");
        }else if(measure.getSystolic() - measure.getDiastolic()<30){
            data.put("脉压差风险评估", "偏低");
        }else{
            data.put("脉压差风险评估", "正常");
        }
        data.put("时间", measure.getUploadTime());
        return data;
    }

    @Override
    public void updateSdhClassification(Long sdhId, Long patientUid) {
        persureHeartRateMapper.updateSdhClassification(sdhId, patientUid);
    }

    @Override
    public JSONObject countSdhClassificationByDoctorAndCare(Long doctorUid) {
        List<Map<String, Object>> result = persureHeartRateMapper.countSdhClassificationByDoctorAndCare(doctorUid);

        List<Integer> levelOneCounts = Arrays.asList(0, 0, 0);
        List<Integer> levelTwoCounts = Arrays.asList(0, 0, 0);
        List<Integer> levelThreeCounts = Arrays.asList(0, 0, 0);

        int total = 0, levelOneTotal = 0, levelTwoTotal = 0, levelThreeTotal = 0;

        for(Map<String, Object> row : result){
            String classification = (String) row.get("sdh_classification");
            Integer count = ((Long) row.get("count")).intValue();
            total += count;

            if(classification.contains("一级高血压")) {
                levelOneTotal += count;
                if(classification.contains("低危")){
                    levelOneCounts.set(0, count);
                } else if(classification.contains("中危")){
                    levelOneCounts.set(1, count);
                } else if(classification.contains("高危")){
                    levelOneCounts.set(2, count);
                }
            } else if (classification.contains("二级高血压")) {
                levelTwoTotal += count;
                if (classification.contains("低危")) {
                    levelTwoCounts.set(0, count);
                } else if (classification.contains("中危")) {
                    levelTwoCounts.set(1, count);
                } else if (classification.contains("高危")) {
                    levelTwoCounts.set(2, count);
                }
            } else if (classification.contains("三级高血压")) {
                levelThreeTotal += count;
                if (classification.contains("低危")) {
                    levelThreeCounts.set(0, count);
                } else if (classification.contains("中危")) {
                    levelThreeCounts.set(1, count);
                } else if (classification.contains("高危")) {
                    levelThreeCounts.set(2, count);
                }
            }
        }

        Map<String, Object> mapData = new LinkedHashMap<>();
        mapData.put("累计", total);
        mapData.put("一级高血压共", levelOneTotal);
        mapData.put("二级高血压共", levelTwoTotal);
        mapData.put("三级高血压共", levelThreeTotal);
        mapData.put("一级高血压", levelOneCounts);
        mapData.put("二级高血压", levelTwoCounts);
        mapData.put("三级高血压", levelThreeCounts);

        JSONObject data = new JSONObject(mapData);

        return data;
    }

    @Override
    public JSONObject nocountSdhClassificationByDoctorAndCare(Long doctorUid) {
        List<Map<String, Object>> result = persureHeartRateMapper.nocountSdhClassificationByDoctorAndCare(doctorUid);

        List<Integer> levelOneCounts = Arrays.asList(0, 0, 0);
        List<Integer> levelTwoCounts = Arrays.asList(0, 0, 0);
        List<Integer> levelThreeCounts = Arrays.asList(0, 0, 0);

        int total = 0, levelOneTotal = 0, levelTwoTotal = 0, levelThreeTotal = 0;
        for(Map<String, Object> row : result){
            String classification = (String) row.get("sdh_classification");
            Integer count = ((Long) row.get("count")).intValue();
            total += count;

            if(classification.contains("一级高血压")) {
                levelOneTotal += count;
                if(classification.contains("低危")){
                    levelOneCounts.set(0, count);
                } else if(classification.contains("中危")){
                    levelOneCounts.set(1, count);
                } else if(classification.contains("高危")){
                    levelOneCounts.set(2, count);
                }
            } else if (classification.contains("二级高血压")) {
                levelTwoTotal += count;
                if (classification.contains("低危")) {
                    levelTwoCounts.set(0, count);
                } else if (classification.contains("中危")) {
                    levelTwoCounts.set(1, count);
                } else if (classification.contains("高危")) {
                    levelTwoCounts.set(2, count);
                }
            } else if (classification.contains("三级高血压")) {
                levelThreeTotal += count;
                if (classification.contains("低危")) {
                    levelThreeCounts.set(0, count);
                } else if (classification.contains("中危")) {
                    levelThreeCounts.set(1, count);
                } else if (classification.contains("高危")) {
                    levelThreeCounts.set(2, count);
                }
            }
        }

        Map<String, Object> mapData = new LinkedHashMap<>();
        mapData.put("累计", total);
        mapData.put("一级高血压共", levelOneTotal);
        mapData.put("二级高血压共", levelTwoTotal);
        mapData.put("三级高血压共", levelThreeTotal);
        mapData.put("一级高血压", levelOneCounts);
        mapData.put("二级高血压", levelTwoCounts);
        mapData.put("三级高血压", levelThreeCounts);

        JSONObject data = new JSONObject(mapData);

        return data;
    }

    @Override
    public Map<String, Long> getDailyStatistics(Long doctorUid) {
        // Fetch the results from the database
        List<Map<String, Object>> resultList = persureHeartRateMapper.selectDailyStatistics(doctorUid);
        Map<String, Long> statisticsMap = new LinkedHashMap<>();

        // Initialize map with 0 counts for the last 10 days
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

        for (int i = 9; i >= 0; i--) {
            String dateKey = today.minusDays(i).format(formatter);
            statisticsMap.put(dateKey, 0L);
        }

        // Fill in actual counts from database results
        for (Map<String, Object> result : resultList) {
            String date = result.get("date").toString();

            // Assuming the date is in yyyy-MM-dd format
            LocalDate localDate = LocalDate.parse(date);

            // Calculate the formatted date
            String formattedDate = localDate.format(formatter);

            // Check if the formattedDate is in the last 10 days
            if (statisticsMap.containsKey(formattedDate)) {
                Long count = ((Number) result.get("count")).longValue();
                statisticsMap.put(formattedDate, count);
            }
        }

        return statisticsMap;
    }


    @Override
    public JSONObject getLastSevenDayAnomalyNum(Long patientUid) {
        List<Map<String, Object>> riskAssessmentCounts = persureHeartRateMapper.getRiskAssessmentCountLastSevenDays(patientUid);

        String[] allRiskLevels = {"重度", "中度", "轻度", "正常高值", "正常", "偏低"};
        JSONObject result = new JSONObject();

        for (String level : allRiskLevels) {
            result.put(level, 0);
        }

        for (Map<String, Object> record : riskAssessmentCounts) {
            String riskAssessment = (String) record.get("risk_assessment");
            if (riskAssessment == null) {
                continue;
            }
            Integer count = ((Long) record.get("count")).intValue(); // 将 count 转换为 Integer
            result.put(riskAssessment, count);
        }

        LocalDate today = LocalDate.now();
        LocalDate sevenDaysAgo = today.minusDays(6);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d");
        String dateRange = sevenDaysAgo.format(formatter) + "~" + today.format(formatter);
        result.put("dateRange", dateRange);

        return result;
    }

    @Override
    public JSONObject getRiskAssessmentNum(Long patientUid, LocalDate date) {
        List<Map<String, Object>> riskAssessmentCounts = persureHeartRateMapper.getRiskAssessmentCountByDate(patientUid, date);

        String[] allRiskLevels = {"重度", "中度", "轻度", "正常高值", "正常", "偏低"};
        JSONObject result = new JSONObject();

        for (String level : allRiskLevels) {
            result.put(level, 0);
        }

        for (Map<String, Object> record : riskAssessmentCounts) {
            String riskAssessment = (String) record.get("risk_assessment");
            if (riskAssessment == null) {
                continue;
            }
            Integer count = ((Long) record.get("count")).intValue();
            result.put(riskAssessment, count);
        }

        return result;
    }

    @Override
    public JSONObject getWeekAnomalyCount(Long patientUid, LocalDate anyDateInWeek) {
        LocalDateTime startOfWeek = anyDateInWeek.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).atStartOfDay();
        LocalDateTime endOfWeek = anyDateInWeek.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).atTime(LocalTime.MAX);

        List<Map<String, Object>> riskAssessmentCounts = persureHeartRateMapper.getRiskAssessmentCountByDataRange(patientUid, startOfWeek, endOfWeek);

        String[] allRiskLevels = {"重度", "中度", "轻度", "正常高值", "正常", "偏低"};
        JSONObject result = new JSONObject();

        // 初始化所有风险等级为0
        for (String level : allRiskLevels) {
            result.put(level, 0);
        }

        // 填充查询结果
        for (Map<String, Object> record : riskAssessmentCounts) {
            String riskAssessment = (String) record.get("risk_assessment");
            if (riskAssessment == null) {
                continue;
            }
            Integer count = ((Long) record.get("count")).intValue(); // 将 count 转换为 Integer
            result.put(riskAssessment, count);
        }

        return result;
    }

    @Override
    public JSONObject getMonthAnomalyCount(Long patientUid, YearMonth month) {
        LocalDate startOfMonth = month.atDay(1);
        LocalDate endOfMonth = month.atEndOfMonth();

        LocalDateTime startDateTime = startOfMonth.atStartOfDay();
        LocalDateTime endDateTime = endOfMonth.atTime(LocalTime.MAX);

        List<Map<String, Object>> riskAssessmentCounts = persureHeartRateMapper.getRiskAssessmentCountByDataRange(patientUid, startDateTime, endDateTime);

        String[] allRiskLevels = {"重度", "中度", "轻度", "正常高值", "正常", "偏低"};
        JSONObject result = new JSONObject();

        for (String level : allRiskLevels) {
            result.put(level, 0);
        }

        for (Map<String, Object> record : riskAssessmentCounts) {
            String riskAssessment = (String) record.get("risk_assessment");
            if (riskAssessment == null) {
                continue;
            }
            Integer count = ((Long) record.get("count")).intValue();
            result.put(riskAssessment, count);
        }

        return result;
    }


    @Override
    public JSONObject getAnomalyCountByDoctorUid(Long doctorUid, boolean care) {
        QueryWrapper<PatientDoctorEntity> queryWrapper = new QueryWrapper<>();
        if (care) {
            queryWrapper.eq("doctor_uid", doctorUid)
                    .eq("care", true);
        } else {
            queryWrapper.eq("doctor_uid", doctorUid);
        }

        List<PatientDoctorEntity> patientDoctorEntities = patientDoctorMapper.selectList(queryWrapper);
        LocalDate now = LocalDate.now();
        LocalDateTime startDateTime = now.atStartOfDay();
        LocalDateTime endDateTime = now.atTime(23, 59, 59);

        logger.info("startDateTime: " + startDateTime);
        logger.info("endDateTime: " + endDateTime);

        int severe = 0, moderate = 0, mild = 0, elevated = 0, low = 0, all = 0;

        for (PatientDoctorEntity patientDoctorEntity : patientDoctorEntities) {
            QueryWrapper<PersureHeartRateEntity> queryWrapper1 = new QueryWrapper<>();

            queryWrapper1.eq("patient_uid", patientDoctorEntity.getPatientUid())
                    .between("upload_time", startDateTime, endDateTime);

            List<PersureHeartRateEntity> anomalyRecords = persureHeartRateMapper.selectList(queryWrapper1);

            for (PersureHeartRateEntity anomalyRecord : anomalyRecords) {
                all++;
                String risk_assessment = anomalyRecord.getRiskAssessment();
                if (risk_assessment != null) {
                    switch (risk_assessment) {
                        case "重度":
                            severe++;
                            break;
                        case "中度":
                            moderate++;
                            break;
                        case "轻度":
                            mild++;
                            break;
                        case "正常高值":
                            elevated++;
                            break;
                        case "偏低":
                            low++;
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        int normal = all - severe - moderate - mild - elevated - low;
        Map<String, Object> mapData = new LinkedHashMap<>();
        mapData.put("重度", severe);
        mapData.put("中度", moderate);
        mapData.put("轻度", mild);
        mapData.put("正常偏高", elevated);
        mapData.put("正常", normal);
        mapData.put("偏低", low);
        mapData.put("累计人次", all);

        JSONObject result = new JSONObject(mapData);
        return result;
    }

    @Override
    public JSONArray getPressureAndRiskByTimeRange(Long patientUid, LocalDate startDate, LocalDate endDate) {
        QueryWrapper<PersureHeartRateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_uid", patientUid)
                .between("upload_time", startDate.atStartOfDay(), endDate.atTime(23, 59, 59))
                .orderByDesc("upload_time");
        List<PersureHeartRateEntity> persureHeartRateEntities = persureHeartRateMapper.selectList(queryWrapper);

        JSONArray results = new JSONArray();

        for(PersureHeartRateEntity entity : persureHeartRateEntities) {
            JSONObject result = new JSONObject();
            if(entity.getRiskAssessment() != null) {
                result.put("systolic", entity.getSystolic());
                result.put("diastolic", entity.getDiastolic());
                result.put("time", entity.getUploadTime());
                result.put("pulsePressure", entity.getSystolic() - entity.getDiastolic());
                result.put("RiskAssessment", entity.getRiskAssessment());
                if(entity.getSystolic() - entity.getDiastolic()>60){
                    result.put("pulsePressureRiskAssessment", "偏高");
                }else if(entity.getSystolic() - entity.getDiastolic()<30){
                    result.put("pulsePressureRiskAssessment", "偏低");
                }else{
                    result.put("pulsePressureRiskAssessment", "正常");
                }

            }
            results.add(result);
        }
        return results;
    }
}